#include "ledcontroller.h"

// 静态常量定义
const QString LedController::LED_BASE_PATH = "/sys/class/leds/";
const QString LedController::BRIGHTNESS_FILE = "/brightness";

LedController::LedController(QObject *parent)
    : QObject(parent)
    , m_ledsBasePath(LED_BASE_PATH)
    , m_statusCheckTimer(new QTimer(this))
{
    // 初始化LED设备
    if (!initializeLeds()) {
        qWarning() << "LED控制器初始化失败";
    }
    
    // 设置状态检查定时器（可选）
    m_statusCheckTimer->setInterval(5000); // 每5秒检查一次
    // connect(m_statusCheckTimer, &QTimer::timeout, this, &LedController::checkAllLedStates);
    
    qDebug() << "LED控制器初始化完成，发现" << m_ledPaths.count() << "个LED设备";
}

LedController::~LedController()
{
    if (m_statusCheckTimer->isActive()) {
        m_statusCheckTimer->stop();
    }
}

bool LedController::initializeLeds()
{
    scanLedDevices();
    return m_ledPaths.count() > 0;
}

void LedController::scanLedDevices()
{
    m_ledPaths.clear();
    m_ledNames.clear();
    
    QDir dir(m_ledsBasePath);
    if (!dir.exists()) {
        qWarning() << "LED设备目录不存在:" << m_ledsBasePath;
        return;
    }
    
    // 获取所有LED设备目录
    QFileInfoList fileInfoList = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
    
    for (const QFileInfo &fileInfo : fileInfoList) {
        QString ledName = fileInfo.fileName();
        
        // 过滤掉不需要的设备（如mmc相关设备）
        if (ledName.contains("mmc") || ledName.contains("phy")) {
            continue;
        }
        
        QString ledPath = m_ledsBasePath + ledName;
        QString brightnessPath = ledPath + BRIGHTNESS_FILE;
        
        // 检查brightness文件是否存在
        QFile brightnessFile(brightnessPath);
        if (brightnessFile.exists()) {
            m_ledPaths.append(ledPath);
            m_ledNames.append(ledName);
            qDebug() << "发现LED设备:" << ledName << "路径:" << ledPath;
        }
    }
    
    qDebug() << "扫描完成，共发现" << m_ledPaths.count() << "个可控制的LED设备";
}

bool LedController::setLedState(int ledIndex, bool on)
{
    if (!isLedValid(ledIndex)) {
        qWarning() << "无效的LED索引:" << ledIndex;
        return false;
    }
    
    QString brightnessPath = getBrightnessPath(ledIndex);
    bool success = writeLedBrightness(brightnessPath, on);
    
    if (success) {
        emit ledStateChanged(ledIndex, on);
        emit ledControlResult(true, QString("LED %1 已%2").arg(m_ledNames[ledIndex]).arg(on ? "开启" : "关闭"));
        qDebug() << "LED" << m_ledNames[ledIndex] << (on ? "开启" : "关闭") << "成功";
    } else {
        emit ledControlResult(false, QString("LED %1 控制失败").arg(m_ledNames[ledIndex]));
        qWarning() << "LED" << m_ledNames[ledIndex] << "控制失败";
    }
    
    return success;
}

bool LedController::getLedState(int ledIndex)
{
    if (!isLedValid(ledIndex)) {
        return false;
    }
    
    QString brightnessPath = getBrightnessPath(ledIndex);
    return readLedBrightness(brightnessPath);
}

bool LedController::toggleLed(int ledIndex)
{
    bool currentState = getLedState(ledIndex);
    return setLedState(ledIndex, !currentState);
}

QString LedController::getLedName(int ledIndex) const
{
    if (ledIndex >= 0 && ledIndex < m_ledNames.count()) {
        return m_ledNames[ledIndex];
    }
    return QString();
}

QStringList LedController::getAllLedNames() const
{
    return m_ledNames;
}

bool LedController::controlLedByName(const QString &ledName, bool on)
{
    int index = m_ledNames.indexOf(ledName);
    if (index != -1) {
        return setLedState(index, on);
    }
    
    // 尝试模糊匹配
    for (int i = 0; i < m_ledNames.count(); ++i) {
        if (m_ledNames[i].contains(ledName, Qt::CaseInsensitive)) {
            return setLedState(i, on);
        }
    }
    
    qWarning() << "未找到名为" << ledName << "的LED设备";
    return false;
}

bool LedController::toggleLedByName(const QString &ledName)
{
    int index = m_ledNames.indexOf(ledName);
    if (index != -1) {
        return toggleLed(index);
    }
    
    // 尝试模糊匹配
    for (int i = 0; i < m_ledNames.count(); ++i) {
        if (m_ledNames[i].contains(ledName, Qt::CaseInsensitive)) {
            return toggleLed(i);
        }
    }
    
    return false;
}

bool LedController::isLedValid(int ledIndex) const
{
    return ledIndex >= 0 && ledIndex < m_ledPaths.count();
}

void LedController::handleVoiceLedCommand(const QString &command)
{
    QString cmd = command.toLower();
    
    qDebug() << "处理LED语音命令:" << command;
    
    // 开启LED命令
    if (cmd.contains("开灯") || cmd.contains("打开灯") || cmd.contains("开启led") || 
        cmd.contains("turn on led") || cmd.contains("led on")) {
        
        if (cmd.contains("全部") || cmd.contains("所有") || cmd.contains("all")) {
            turnOnAllLeds();
        } else {
            // 尝试识别具体的LED名称
            bool found = false;
            for (int i = 0; i < m_ledNames.count(); ++i) {
                if (cmd.contains(m_ledNames[i].toLower())) {
                    setLedState(i, true);
                    found = true;
                    break;
                }
            }
            if (!found && m_ledPaths.count() > 0) {
                // 如果没有指定具体LED，控制第一个
                setLedState(0, true);
            }
        }
    }
    // 关闭LED命令
    else if (cmd.contains("关灯") || cmd.contains("关闭灯") || cmd.contains("关闭led") || 
             cmd.contains("turn off led") || cmd.contains("led off")) {
        
        if (cmd.contains("全部") || cmd.contains("所有") || cmd.contains("all")) {
            turnOffAllLeds();
        } else {
            // 尝试识别具体的LED名称
            bool found = false;
            for (int i = 0; i < m_ledNames.count(); ++i) {
                if (cmd.contains(m_ledNames[i].toLower())) {
                    setLedState(i, false);
                    found = true;
                    break;
                }
            }
            if (!found && m_ledPaths.count() > 0) {
                // 如果没有指定具体LED，控制第一个
                setLedState(0, false);
            }
        }
    }
    // 切换LED状态命令
    else if (cmd.contains("切换灯") || cmd.contains("反转led") || cmd.contains("toggle led")) {
        
        if (cmd.contains("全部") || cmd.contains("所有") || cmd.contains("all")) {
            toggleAllLeds();
        } else {
            // 尝试识别具体的LED名称
            bool found = false;
            for (int i = 0; i < m_ledNames.count(); ++i) {
                if (cmd.contains(m_ledNames[i].toLower())) {
                    toggleLed(i);
                    found = true;
                    break;
                }
            }
            if (!found && m_ledPaths.count() > 0) {
                // 如果没有指定具体LED，控制第一个
                toggleLed(0);
            }
        }
    }
    else {
        qDebug() << "未识别的LED控制命令:" << command;
        emit ledControlResult(false, "未识别的LED控制命令");
    }
}

void LedController::turnOnAllLeds()
{
    bool allSuccess = true;
    for (int i = 0; i < m_ledPaths.count(); ++i) {
        if (!setLedState(i, true)) {
            allSuccess = false;
        }
    }
    
    if (allSuccess) {
        emit allLedsStateChanged(true);
        emit ledControlResult(true, "所有LED已开启");
    } else {
        emit ledControlResult(false, "部分LED开启失败");
    }
}

void LedController::turnOffAllLeds()
{
    bool allSuccess = true;
    for (int i = 0; i < m_ledPaths.count(); ++i) {
        if (!setLedState(i, false)) {
            allSuccess = false;
        }
    }
    
    if (allSuccess) {
        emit allLedsStateChanged(false);
        emit ledControlResult(true, "所有LED已关闭");
    } else {
        emit ledControlResult(false, "部分LED关闭失败");
    }
}

void LedController::toggleAllLeds()
{
    for (int i = 0; i < m_ledPaths.count(); ++i) {
        toggleLed(i);
    }
    emit ledControlResult(true, "所有LED状态已切换");
}

QString LedController::getBrightnessPath(int ledIndex) const
{
    if (isLedValid(ledIndex)) {
        return m_ledPaths[ledIndex] + BRIGHTNESS_FILE;
    }
    return QString();
}

bool LedController::writeLedBrightness(const QString &path, bool on)
{
    QFile file(path);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qWarning() << "无法打开LED文件进行写入:" << path;
        return false;
    }
    
    QTextStream out(&file);
    out << (on ? "1" : "0");
    file.close();
    
    return true;
}

bool LedController::readLedBrightness(const QString &path)
{
    QFile file(path);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "无法打开LED文件进行读取:" << path;
        return false;
    }
    
    QTextStream in(&file);
    QString content = in.readAll().trimmed();
    file.close();
    
    return content == "1";
} 